import {
  getItemForPk,
  haveDeviceTimeCorrect,
  isSupportPasswordVerify,
  isBLE,
  getConfigSupportShareFromPK,
  getConfigSupportShare,
} from '@/config/product';
import deviceDataModel from '@/models/deviceData';
import deviceDetailModel from '@/models/deviceDetail';
import deviceListModel from '@/models/deviceList';
import deviceShare from '@/models/deviceShare';
import gizwitsSdk from '@/models/gizwitsSdk';
import homes from '@/models/homes';
import { filterDeviceCanShare } from '@/pages/share/shareList/models';
import { queryAggregate } from '@/services/aggregateData';
import { getDeviceAiList, getAiUseProductList, updateAiUseProductList, getAiSelfVoiceList, getSystemVoiceList, deleteDeviceContext, getRecordText, newCopyVoice, createUserAgent, updateUserAgent, deleteUserAgent, getUserAgent, getUserAgentList, getDeviceMessages, getDeviceOtaTask, pushDeviceOtaTask, confirmDeviceOtaTask } from '@/services/ai';
import { queryDataPoint } from '@/services/openApi';
import Toast from '@/utils/Toast';
import Taro from '@tarojs/taro';
import i18n from 'i18n-js';
import SecureStore from '@/utils/AsyncStorage';
import { toJS } from 'mobx';

interface IUniversalMenuItem {
  title: string;
  onPress: () => void;
  id: string;
}

const serviceKey = 'templateService.serviceKey';



function makeKey(templateId, key) {
  return `${serviceKey}:${templateId}:${key}`;
}

class AppService {
  isSupportDeviceInfoPage = () => {
    if (deviceDetailModel.device && !deviceDetailModel.device.groupID && !deviceDetailModel.device.isVirtual) {
      return true;
    }
    return false;
  };

  isSupportUniversalMenu = () => {
    if (deviceDetailModel.device) {
      return true;
    }
    return false;
  };

  isSupportUniversalMenuAsync = async () => {
    return await this.isSupportUniversalMenu();
  };

  isSupportShare() {
    return (
      deviceDetailModel.device && !deviceDetailModel.device.isVirtual && filterDeviceCanShare(deviceDetailModel.device)
    );
  }

  // 跳转到设备信息页面
  goDeviceInfoPage = () => {
    Taro.navigateTo({ url: '/pages/deviceInfo/index' });
  };

  goHelpCenter = () => {
    Taro.navigateTo({ url: '/pages/deviceHelp/index?type=FromDevice' });
  };

  goDeviceAlarmSetting = () => {
    if (!deviceDetailModel.device) {
      return;
    }
    const { mac, productKey } = deviceDetailModel.device;
    Taro.navigateTo({ url: `/pages/deviceAlarm/setting?mac=${mac}&productKey=${productKey}` });
  };

  goDeviceShare = () => {
    if (!deviceDetailModel.device) {
      return;
    }
    const { mac, productKey } = deviceDetailModel.device;
    Taro.navigateTo({ url: `/pages/share/modes/index?mac=${mac}&productKey=${productKey}` });
  };

  goOta = () => {
    const { mac, productKey, id } = deviceDetailModel.device;
    Taro.navigateTo({ url: `/pages/ota/index?mac=${mac}&productKey=${productKey}&id=${id}` });
  }
  getUniversalMenu = () => {
    // 二维数组，第一层之间会有菜单间隔，第二层菜单是连接在一起的，没有间隔
    const oneMenuList: IUniversalMenuItem[] = [];
    if (this.isSupportDeviceInfoPage()) {
      oneMenuList.push({ title: i18n.t('DEVICE_INFO'), onPress: this.goDeviceInfoPage, id: 'deviceInfo' });
    }

    // if (this.isSupportTimeCorrect()) {
    //   oneMenuList.push({ title: i18n.t('TIME_CORRECT'), onPress: this.showTimeCorrect, id: 'timeCorrect' });
    // }

    if (this.isSupportPasswordVerify()) {
      oneMenuList.push({ title: i18n.t('LOCK'), onPress: this.goToPasswordSetPage, id: 'setLock' });
    }

    oneMenuList.push({ title: i18n.t('USE_HELP'), onPress: this.goHelpCenter, id: 'deviceUseHelp' });

    oneMenuList.push({ title: i18n.t('OTA'), onPress: this.goOta, id: 'ota' });

    if (this.isSupportShare()) {
      oneMenuList.push({ title: i18n.t('DEVICE_SHARE'), onPress: this.goDeviceShare, id: 'deviceShare' });
    }
    if (
      deviceDetailModel.device &&
      !deviceShare.isShareToMeDevice(deviceDetailModel.device) &&
      deviceDetailModel.productConfig?.supportDeviceAlarm
    ) {
      oneMenuList.push({ title: i18n.t('ALARM_PUSH'), onPress: this.goDeviceAlarmSetting, id: 'deviceAlarmSetting' });
    }
    return [oneMenuList];
  };

  getUniversalMenuAsync = async () => {
    return this.getUniversalMenu();
  };

  getConfigForPK() {
    const config = deviceDetailModel.productConfig || getItemForPk(deviceDetailModel.device?.productKey) || {};
    return config.templateConfig || {};
  }
  deviceDataUpdate(data) {
    deviceDetailModel.virtualDeviceSendCmd(data);
  }
  async sendCmd(data) {
    if (deviceDetailModel.device) {
      if (deviceDetailModel.device.isVirtual) {
        return await deviceDetailModel.virtualDeviceSendCmd(data);
      } else {
        return await deviceDetailModel.sendCmd(data);
      }
    }
    return { success: false };
  }

  async sendBroadCastBigData(data: number[]) {
    return await deviceDetailModel.sendBroadCastBigData(data);
  }

  async sendCmdChunk(data, timeout = 1000) {
    if (deviceDetailModel.device) {
      if (deviceDetailModel.device.isVirtual) {
        return await deviceDetailModel.virtualDeviceSendCmd(data);
      } else {
        return await deviceDetailModel.sendCmdChunk(data, timeout);
      }
    }
    return { success: false };
  }

  sendCmdLimit(data) {
    if (deviceDetailModel.device) {
      if (deviceDetailModel.device.isVirtual) {
        return deviceDetailModel.virtualDeviceSendCmd(data);
      } else {
        return gizwitsSdk.sendCmdLimit({ device: deviceDetailModel.device, data });
      }
    }
    return { success: false };
  }

  async getDeviceStatus({ attrs }) {
    if (deviceDetailModel.device) {
      if (deviceDetailModel.device.isVirtual) {
        return {};
      } else {
        const data = await gizwitsSdk.getDeviceStatus({ device: deviceDetailModel.device, attrs });
        return data;
      }
    }
    return {};
  }

  back() {
    deviceDataModel.allBackToHome();
  }

  isSupportDelete() {
    if (deviceDetailModel.device) {
      return true;
    }
    return false;
  }

  isSupportDeleteAsync = async () => {
    return await this.isSupportDelete();
  };

  async deleteDevice() {
    // console.log('删除设备');
    if (deviceDetailModel.device && this.isSupportDelete()) {
      if (deviceDetailModel.device.isVirtual) {
        // this.back();
        Toast.info(i18n.t('DEMO_DEVICE_DONT_SUPPORT_THIS_OPERATION'));
        return { success: true };
      } else {
        const [data] = await homes.deleteDevices([deviceDetailModel.device]);
        if (data?.success) {
          this.back();
        }
        return data || { success: false };
      }
    }
    return { success: false };
  }


  isSupportRename() {
    if (deviceDetailModel.device && !deviceShare.isShareToMeDevice(deviceDetailModel.device)) {
      return true;
    }
    return false;
  }

  isSupportRenameAsync = async () => {
    return this.isSupportRename();
  };

  async renameDevice(name, device?) {
    if (!this.isSupportRename()) {
      return { success: false };
    }
    if (deviceDetailModel.device && deviceDetailModel.device.isVirtual) {
      // deviceDetailModel.virtualRenameDevice(name);
      Toast.info(i18n.t('DEMO_DEVICE_DONT_SUPPORT_THIS_OPERATION'));
      return { success: true };
    }
    return homes.renameDevice({ device: device || deviceDetailModel.device, name });
  }

  async getDataPoint() {
    if (deviceDetailModel.device) {
      const data = await queryDataPoint(deviceDetailModel.device);
      console.log('datat =', data);
      return data.success ? data.data : null;
    }
    return { success: false };
  }

  checkDeviceOwner = () => {
    if (deviceDetailModel.device) {
      return homes.checkDeviceOwner(deviceDetailModel.device);
    }
    return false;
  };

  isSupportTimeCorrect = () => {
    return !!deviceDetailModel.productConfig && haveDeviceTimeCorrect(deviceDetailModel.productConfig);
  };

  showTimeCorrect = () => {
    if (this.isSupportTimeCorrect()) {
      deviceDetailModel.setDeviceTimeCorrectModal(true);
    }
  };

  // 正常不需要调hide
  hideTimeCorrect = () => {
    deviceDetailModel.setDeviceTimeCorrectModal(false);
  };

  // 查询聚合数据
  aggregateData = async (params: any) => {
    return await queryAggregate({
      did: deviceDetailModel.device?.did,
      ...params,
    });
  };

  isSupportPasswordVerify = () => {
    console.log(deviceDetailModel.productConfig);
    return !!deviceDetailModel.productConfig && isSupportPasswordVerify(deviceDetailModel.productConfig);
  };

  goToPasswordSetPage = () => {
    Taro.navigateTo({ url: '/pages/deviceLock/index' });
  };

  asyncSetStorage = (key, ...args) => {
    return Taro.setStorageSync(makeKey(deviceDetailModel.productConfig?.wxTemplateId, key), args);
  };

  asyncGetStorage = key => {
    return Taro.getStorageSync(makeKey(deviceDetailModel.productConfig?.wxTemplateId, key));
  };

  isSupportScheduler = () => {
    if (
      deviceDetailModel.device &&
      !deviceDetailModel.device.isVirtual &&
      !isBLE(deviceDetailModel.productConfig!) &&
      deviceDetailModel.productConfig &&
      deviceDetailModel.productConfig.schedulerConfig &&
      deviceDetailModel.productConfig.schedulerConfig.length > 0
    ) {
      return true;
    }
    return false;
  };

  goToScheduler = () => {
    Taro.navigateTo({ url: '/pages/scheduler/index' });
  };

  setDeviceRemark = (remark: string) => {
    return deviceListModel.setDeviceRemark({ device: deviceDetailModel.device, remark });
  };

  isSupportTimeCorrectAsync = async () => {
    return await this.isSupportTimeCorrect();
  };
  checkDeviceOwnerAsync = async () => {
    return await this.checkDeviceOwner();
  };
  renameDeviceAsync = async name => {
    return await this.renameDevice(name);
  };

  deleteDeviceAsync = async () => {
    return await this.deleteDevice();
  };

  // 产品智能体
  getAiList = async () => {
    const data = await getDeviceAiList({ id: deviceDetailModel.device?.id });
    console.log('getAiList', data)
    return data
  }
  // 设备使用智能体
  getAiUseList = async () => {
    const uid = await SecureStore.getItem('uid');
    const deviceId = deviceDetailModel.device?.id
    const data = await getAiUseProductList({ user_id: uid, device_id: deviceId });
    return data
  }
  getRecordText = async () => {
    const uid = await SecureStore.getItem('uid');
    const data = await getRecordText({ user_id: uid });
    return data
  }

  getAiMessage = async ({ agent_id, cursor, limit }) => {
    const deviceId = deviceDetailModel.device?.id || ""
    const data = await getDeviceMessages({ agent_id, device_id: deviceId, cursor, limit });
    return data
  }

  newCopyVoice = async ({path, voice_id, name, content}) => {
    const uid = await SecureStore.getItem('uid');
    const data = await newCopyVoice({ user_id: uid, path: path, voice_id: voice_id, name: name, content: content });
    return data
  }
  // 更新使用智能体
  updateAiUse = async (agentid, voiceid) => {
    const uid = await SecureStore.getItem('uid');
    const deviceId = deviceDetailModel.device?.id
    const data = await updateAiUseProductList({ user_id: uid, device_id: deviceId, agent_id: agentid, voice_id: voiceid });
    console.log('999999999', data)
    return data;
  }
  // 自定义列表获取
  getSelfList = async () => {
    const uid = await SecureStore.getItem('uid');
    const data = await getAiSelfVoiceList({ user_id: uid });
    return data
  }

  createUserAgent = async (params) => {
    const uid = await SecureStore.getItem('uid');
    const data = await createUserAgent({ user_id: uid, ...params });
    return data
  }
  getUserAgentList = async () => {
    const uid = await SecureStore.getItem('uid');
    const data = await getUserAgentList({ user_id: uid });
    return data
  }
  updateUserAgent = async (agent_id, params) => {
    const data = await updateUserAgent(agent_id, { ...params });
    return data
  }
  deleteUserAgent = async (agent_id) => {
    const data = await deleteUserAgent(agent_id);
    return data
  }
  getUserAgent = async (agent_id) => {
    const data = await getUserAgent(agent_id);
    return data
  }

  // 系统音色列表获取
  getSystemVoiceList = async (agent_id) => {
    const data = await getSystemVoiceList({ product_key: deviceDetailModel.device?.productKey, agent_id: agent_id });
    return data
  }

  // 删除上下文
  deleteContext = async () => {
    const deviceId = deviceDetailModel.device?.id
    const data = await deleteDeviceContext(deviceId);
    return data
  }

  // 获取设备可升级固件列表
  getDeviceOtaTask = async () => {
    const deviceId = deviceDetailModel.device?.id;
    if (!deviceId) return { success: false };
    
    const data = await getDeviceOtaTask(deviceId);
    return data;
  }

  // 推送设备可升级固件
  pushDeviceOtaTask = async (taskId: string) => {
    const deviceId = deviceDetailModel.device?.id;
    if (!deviceId) return { success: false };
    
    const data = await pushDeviceOtaTask(deviceId, taskId);
    return data;
  }

  // 确认设备可升级固件
  confirmDeviceOtaTask = async (taskId: string) => {
    const deviceId = deviceDetailModel.device?.id;
    if (!deviceId) return { success: false };
    
    const data = await confirmDeviceOtaTask(deviceId, taskId);
    return data;
  }

}


export default new AppService();
